package cn.wgj;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.Date;
import java.util.Properties;

/**
 * Hello world!
 *
 */
public class App {
    private String basePath;
    private Scanner sc = new Scanner(System.in);
    private String resourcePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

    public static void main(String[] args) {
        new App().applicationStart();
    }

    /**
     * 启动程序
     *
     * @param basePath
     */
    public void applicationStart() {
        boolean flag = true;
        while (flag) {
            String basePath = getPath();
            System.out.println("=============================");
            System.out.println("当前路径：" + basePath);
            File f = new File(basePath);
            if (f.exists()) {
                System.out.println("选择要进行的操作（按q退出）");
                System.out.print("1.创建文件夹\t\t");
                System.out.print("2.创建文件\t\t\n");
                System.out.print("3.修改文件夹名\t\t");
                System.out.print("4.删除文件夹\t\t\n");
                System.out.print("5.修改改当前路径\t");
                System.out.print("6.列出文件和文件夹\t\t\n");
            } else {
                System.out.println("当前路径不存在，必须重新设置");
                changePath();
                continue;
            }
            System.out.println("=============================");
            String choice = sc.next();
            if (choice.equals("q") || choice.equals("Q")) {
                flag = false;
            }
            int c;
            try {
                c = Integer.parseInt(choice);
            } catch (Exception e) {
                continue;
            }
            switch (c) {
            case 1:
                mkDir(basePath);
                break;
            case 2:
                mkFile(basePath);
                break;
            case 3:
                rename(basePath);
                break;
            case 4:
                delete(basePath);
                break;
            case 5:
                changePath();
                break;
            case 6:
                listFiles(basePath);
                break;
            default:
                break;
            }
        }
        sc.close();
    }

    /**
     * 创建文件夹
     */
    public void mkDir(String basePath) {
        String path = basePath;
        System.out.println("输入文件夹名?");
        String decName = sc.next();
        path = pathProcess(path, decName);
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        } else {
            String[] paths = path.split("/");
            System.out.println(paths[paths.length - 1] + "has exits");
        }
    }

    /**
     * 对路径的处理
     *
     * @param path
     * @param decName
     * @return
     */
    private String pathProcess(String path, String decName) {
        if (path.endsWith("/")) {
            path += decName;
        } else if (path.endsWith("\\\\")) {
            path += decName;
        } else if (path.endsWith("\\")) {
            path += "\\" + decName;
        } else {
            path += "/" + decName;
        }
        return path;
    }

    /**
     * 修改文件夹名称
     *
     * @param basePath
     * @return
     *
     *         todo
     */
    public String rename(String basePath) {
        int lastIndexOf = basePath.lastIndexOf("/");
        int dirNum = sc.nextInt();
        String path = basePath.substring(0, lastIndexOf + 1) + dirNum;
        sc.close();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
            return path;
        } else {
            String[] paths = path.split("/");
            System.out.println(paths[paths.length - 1] + "has exits");
        }
        return "";
    }

    /**
     * 删除文件夹
     *
     * @param basePath
     */
    public void delete(String basePath) {
        listFiles(basePath);
        System.out.println("输入想要删除的文件夹名称：");
        String name = sc.next();
        basePath = pathProcess(basePath, name);
        File file = new File(basePath);
        if (file.exists() && file.isDirectory()) {
            System.out.println("确定删除" + name + "及其所有文件吗?(Y/N)");
            String chioce = sc.next();
            if (chioce.equals("Y") || chioce.equals("y")) {
                delDir(basePath);
            }
        } else if (!file.exists()) {
            System.out.println("文件夹不存在");
        } else {
            System.out.println("不能删除文件");
        }
    }

    /**
     * 递归删除操作
     *
     * @param basePath
     */
    private void delDir(String basePath) {
        File file = new File(basePath);
        if (file.isFile()) {
            file.delete();
        } else {
            File[] files = file.listFiles();
            if (files == null) {
                file.delete();
            } else {
                for (int i = 0; i < files.length; i++) {
                    delDir(files[i].getAbsolutePath());
                }
                file.delete();
            }
        }
    }

    /**
     * 创建文件
     *
     *
     */
    public void mkFile(String basePath) {
        boolean flag = true;
        while (flag) {
            System.out.println("=============================");
            System.out.println("当前路径：" + basePath);
            System.out.println("选择文件夹（/表示选择当前路径?(q退出当前操作)）：");
            listFiles(basePath);
            String name = sc.next();
            if (name.equals("/")) {
                name = "";
            } else if (name.equals("q")) {
                break;
            }
            String path = pathProcess(basePath, name);
            File f = new File(path);
            if (f.exists()) {
                System.out.println("当前路径：" + path);
                System.out.println("选择要进行的操作（按q退出）?");
                System.out.print("1.创建单个文件\t");
                System.out.print("2.创建多个文件\t\n");
                // TODO
                System.out.print("3.自定义模式(正则表达式)\t\n");
            } else {
                System.out.println("当前路径不存在，必须重新设置");
                continue;
            }
            System.out.println("=============================");
            String choice = sc.next();
            if (choice.equals("q") || choice.equals("Q")) {
                flag = false;
            }
            int c;
            try {
                c = Integer.parseInt(choice);
            } catch (Exception e) {
                continue;
            }
            switch (c) {
            case 1:
                mkFile1(path);
                break;
            case 2:
                mkFiles(path);
                break;
            case 3:
                mkFileCustom(path);
                break;
            default:
                break;
            }
        }
    }

    /**
     * 自定义
     *
     * @param basePath2
     */
    private void mkFileCustom(String basePath2) {
        boolean flag = true;
        int p1, p2 = 1, p3;
        while (flag) {
            System.out.print("输入三个参数(ex?_?.cpp) 空格分隔");
            System.out.print("输入q/Q退出当前操作?");
            System.out.println("后两个参数为start end(start可选，默认为1)");
            String line = sc.nextLine();
            String params[] = line.split(" ");
            if (params.length == 1) {
                if (params[0].equals("q") || params[0].equals("Q")) {
                    return;
                }
            } else if (params.length == 2) {
                p2 = 1;
            } else {
                try {
                    p2 = Integer.parseInt(params[1]);
                } catch (Exception e) {
                    System.out.println("参数有误");
                    continue;
                }
            }
            try {
                p1 = Integer.parseInt(params[0]);
                p3 = Integer.parseInt(params[params.length - 1]);
            } catch (Exception e) {
                System.out.println("参数有误");
                continue;
            }
            for (int i = p2; i <= p3; ++i) {
                String fileName = "ex" + p1 + "_" + i + ".cpp";
                String path = pathProcess(basePath2, fileName);
                File file = new File(path);
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            flag = false;
        }
        listFiles(basePath2);
    }

    /**
     * 创建多个文件
     */
    private void mkFiles(String path) {
        System.out.println("输入文件个数：");
        int num;
        try {
            num = Integer.parseInt(sc.next());
        } catch (Exception e) {
            System.out.println("输入有误");
            return;
        }
        for (int i = 0; i < num; i++) {
            mkFile(path);
        }
    }

    /**
     * 创建单个文件
     *
     * @param path
     */
    private void mkFile1(String path) {
        System.out.println("输入文件完全名称（包括文件后缀）");
        String fileName = sc.next();
        String filePath = pathProcess(path, fileName);
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            System.out.println("文件已经存在，是否覆盖（Y?）");
            String choice = sc.next();
            if (choice.equals("Y") || choice.equals("y")) {
                file.delete();
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        listFiles(path);
        try {
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 显示文件列表
     *
     * @param basePath
     */
    private void listFiles(String basePath) {
        File[] files = new File(basePath).listFiles();
        for (File file : files) {
            System.out.println(file.getName());
        }
    }

    /**
     * 读取配置路径
     */
    public String getPath() {
        FileInputStream fis = null;
        InputStream in = null;
        try {
            fis = new FileInputStream(new File(resourcePath + "App.properties"));
            in = new BufferedInputStream(fis);
            Properties prop = new Properties();
            prop.load(in);
            basePath = prop.getProperty("basePath");
        } catch (FileNotFoundException e) {
            System.out.println("properties文件路径需要检查！");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return basePath;
    }

    public void changePath() {
        System.out.print("输入路径:");
        String path = sc.next();
        Properties properties = new Properties();
        OutputStream output = null;
        try {
            output = new FileOutputStream(resourcePath + "App.properties");
            properties.setProperty("basePath", path);
            properties.store(output, "wgj1993 modify" + new Date().toString());
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
